package hc.bre.runner

import javax.annotation.PostConstruct

import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component

import net.bytebuddy.implementation.bind.annotation.Super

@groovy.transform.CompileStatic
class ScriptEngineRunner extends RuleRunnerSupport {
	GroovyScriptEngine scriptEngine;

	ScriptEngineRunner(String ruledir) {
		if(!ruledir.endsWith(File.separator)) {
			ruledir = ruledir + File.separator
		};
		this.ruledir = ruledir

		scriptEngine = new GroovyScriptEngine(this.ruledir);
	}

	//TODO, support return user bean type support
	protected Object runProject(String projPath, Map variables)
	{
		Binding binding = new Binding(variables)
		return scriptEngine.run(projPath, binding)
	}

	public Object run(Map namedArgsMap)
	{
		def projPath = hc.Util.rpathPrjectCode(namedArgsMap['_entry_'] as String) +'/Main.groovy'

		return runProject(projPath, namedArgsMap)
	}


	public Object run(String rpath, Object namedArgsMap)
	{
		Map variables;
		//TODO check and support other class, such as Expando class
		if(namedArgsMap instanceof Map)
		{
			variables = namedArgsMap;
		}
		else if(namedArgsMap== null){
			variables = [:];
		}else{
			variables =  namedArgsMap.properties;
			variables.remove('class');
		}

		if(!variables.containsKey('_entry_'))
			variables.put('_entry_', rpath);

		def projPath = hc.Util.rpathPrjectCode(rpath) +'/Main.groovy'

		return runProject(projPath, variables)
	}
}
